package com.gmlive.common.host.retrofit

import android.util.Log
import com.gmlive.common.host.model.BaseModel
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.HttpException
import retrofit2.Response
import java.net.ConnectException

/**
 * Created by ZhongJianXin
 * on 2019-10-23
 * desc
 */


abstract class BaseCallback<T> : Callback<T> {

    protected abstract fun onSuccess(t: T?)

    protected abstract fun onFailed(code: Int, msg: String?)

    override fun onResponse(call: Call<T>, response: Response<T>) {
        val baseModel = response.body()
        if (response.isSuccessful && baseModel != null) {
            try {
                if (baseModel is String) {
                    val jsonObject = JSONObject(baseModel)
                    val dm_error = jsonObject.optInt("dm_error")
                    if (dm_error == 0) {
                        onSuccess(baseModel)
                    } else {
                        onFailed(dm_error, jsonObject.optString("error_msg"))
                    }
                } else if (baseModel is BaseModel<*>) {
                    if (baseModel.isSuccess() && baseModel.data != null) {
                        onSuccess(baseModel)
                    } else {
                        onFailed(baseModel.dm_error, baseModel.error_msg)
                    }
                }
            } catch (e: Exception) {
                Log.e("BaseCallback", "Exception：" + e.message)
                onFailed(response.code(), response.message())
            }

        } else {
            onFailed(response.code(), response.message())
        }
    }

    override fun onFailure(call: Call<T>, t: Throwable) {
        when (t) {
            is ConnectException -> //网络连接失败
                onFailed(403, t.message)
            is HttpException -> onFailed(t.code(), t.message())
            else -> onFailed(405, t.message)
        }
    }
}